const express = require('express')
const router = express.Router()
const { query } = require('../db')
// 用户列表
router.get('/list',async (req,res,next) => {
  // 获取get传递的参数
  const obj = req.query
  console.log(obj)
  // 条件拼接
  // 姓名和性别存在
  // 姓名存在
  // 性别存在
  let page = 10
  let str = ''
  if(obj.uname && obj.sex) {
    str = `where uname like '%${obj.uname}%' && sex=${obj.sex}`
  } else if(obj.uname) {
    str = `where uname like '%${obj.uname}%'`
  } else if(obj.sex) {
    str = `where sex=${obj.sex}`
  }
  // 判断页码
  if(!obj.pno) {
    obj.pno = 1
  }
  // 计算开始查询的值
  let start = (obj.pno-1) * page
  // 执行SQL命令
  try {
    var data = await query(`select * from hs_user ${str} order by id desc limit ${start},${page};select count(*) n from hs_user ${str}`)
  } catch(err) {
    return next(err)
  }
  console.log(data)
  res.send({
    code: 200,
    msg: '用户列表',
    data: data[0],
    total: data[1][0].n,
    pno: obj.pno
  })
})
// 用户健康档案(get /health)
router.get('/health', async (req,res,next) => {
  // 获取用户的id
  const { id } = req.query
  if(!id) {
    return res.send({
      code: 401,
      msg: 'id不能为空'
    })
  }
  // 通过id查询对应的列表
  try {
    var data = await query('select * from hs_health where user_id=?',[id])
  } catch(err) {
    return next(err)
  }
  // 响应
  res.send({
    code: 200,
    msg: '用户下健康档案',
    data 
  })
})
// 健康档案列表(get /healthList)
router.get('/healthList', async (req,res,next) => {
  // 获取get传递的参数
  const obj = req.query
  console.log(obj)
  let page = 10
  // 判断条件
  let str = ''
  // 姓名和性别都存在
  // 姓名存在
  // 性别存在
  if(obj.name && obj.sex) {
    str = `where a.name like '%${obj.name}%' && a.sex=${obj.sex}`
  } else if(obj.name) {
    str = `where a.name like '%${obj.name}%'`
  } else if(obj.sex) {
    str = `where a.sex=${obj.sex}`
  } else {
    str = `where 1`
  }
  // 判断页码是否为空
  if(!obj.pno) {
    obj.pno = 1
  }
  // 计算出开始查询的值
  let start = (obj.pno - 1) * page
  // 执行SQL命令
  try {
    var data = await query(`select a.id,a.name,a.sex,a.birthday,a.phone,a.history,a.family,b.uname from hs_health a,hs_user b ${str} && a.user_id=b.id order by id desc limit ${start},${page};select count(*) n from hs_health a,hs_user b ${str} && a.user_id=b.id`)
  } catch(err) {
    return next(err)
  }
  console.log(data)

  res.send({
    code: 200,
    msg: '档案列表',
    data: data[0],
    total: data[1][0].n,
    pno: obj.pno
  })
})
module.exports = router